﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.GIMS.BLL;
using KPIS.GERP.GIMS.IBLL;
using KPIS.GERP.GIMS.MODEL;
using System.Data;
using System.IO;

namespace KPIS.GERP.GIMS.APP.APP_UI.Add_Form
{
    public partial class ICM_Pre_Purchase_Request : System.Web.UI.Page
    {
        Common.Main cn = new Common.Main();
        CommandControl cmdFac = new CommandControl();
        IBLLPrePurchaseRequest bll = new PrePurchaseRequestBLL();
        IBLLTree bllTree = new TreeBLL();
        IBLLMasterPurchaseType bllPurchaseType = new MasterPurchaseTypeBLL();
        IBLLMasterPurchaseMapping bllPurchaseMap = new MasterPurchaseMappingBLL();
        IBLLMasterPurchaseRule bllRule = new MasterPurchaseRuleBLL();
        //IBLLSysPprPriority bllPprPriority = new SysPprPriorityBLL();
        //IBLLSysPprType bllPprType = new SysPprTypeBLL();
        //IBLLSysPprMethod bllPprMethod = new SysPprMethodBLL();
        IBLLMasterPurchaseType bllPcType = new MasterPurchaseTypeBLL();
        IBLLBgmSource bllSource = new BgmSourceBLL();
        IBLLResourceMasterItem bllItem = new ResourceMasterItemBLL();
        IBLLBgmProject bllProject = new BgmProjectBLL();
        IBLLBgmProjectExpense bllProjectExpense = new BgmProjectExpenseBLL();
        IBLLBgmProjectOperation bllOperation = new BgmProjectOperationBLL();
        IBLLBgmProjectOperationExpense bllOperationExpense = new BgmProjectOperationExpenseBLL();
        IBLLMasterCommitteeFunction bllComFunction = new MasterCommitteeFunctionBLL();
        IBLLMasterCommitteePosition bllComPosition = new MasterCommitteePositionBLL();
        IBLLMasterCommitteeMapping bllComMapping = new MasterCommitteeMappingBLL();
        IBLLHrmEmployee bllEmployee = new HrmEmployeeBLL();
        IBLLSysDurationCount bllDurationCount = new SysDurationCountBLL();
        IBLLSysDurationType bllDurationType = new SysDurationTypeBLL();
        IBLLSysPprUseMethod bllUseMethod = new SysPprUseMethodBLL();
        IBLLPersonal bllPersonal = new PersonalBLL();
        IBLLSysYearType bllYearType = new SysYearTypeBLL();
        HrmJobSiteBLL bllJobSite = new HrmJobSiteBLL();

        double sumValue = 0;
        double totalPrice = 0;
        int nCount = 0;
        private const int ItemsPerRequest = 10;
        string YearType = "";
        string Year = "";
        string PurchaseType = "";
        string UseMethod = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString.Count > 0)
                {
                    YearType = Session["yearSeq"].ToString();
                    cbYearType.SelectedValue = YearType;

                    Year = Session["year"].ToString();
                    txtYear.Text = Year;
                    PurchaseType = Request.QueryString["pt"].ToString();
                    Session["PurchaseType"] = PurchaseType;
                    lblPurchaseType.Text = bllPurchaseType.GetMasterPurchaseType(Convert.ToInt32(PurchaseType)).Name;
                    UseMethod = Request.QueryString["um"].ToString();
                    Session["UseMethod"] = UseMethod;
                    //lblUseMethod.Text = bllUseMethod.GetSysPprUseMethod(Convert.ToInt32(UseMethod)).Name;
                }
                GetUserJobSite(Int32.Parse(Session["EmpSeq"].ToString()));
                //LoadProjectTree();
                //LoadOperationTree();
                //LoadRootNodes(TreeItem, TreeNodeExpandMode.ServerSideCallBack);
                LoadGridItem();
                LoadGridCommittee();
                LoadCommitteeFunction();
                LoadCommitteePosition();
                LoadGridFile();
                LoadGridSubCommittee();
                LoadDurationType();
                LoadDurationCount();
                //LoadJobSiteTree(); // Amp Method
                LoadYearType(); // Amp Method
                panelDateReq.Attributes.Add("style", "visibility:hidden");
                panelDateReqPick.Attributes.Add("style", "visibility:hidden");
                rdbDuration.Attributes.Add("onclick", "return ChangeDurationRequire('" + panelDuration.ClientID + "','" + panelDateReq.ClientID + "','" + panelDateReqPick.ClientID + "')");
                rdbDate.Attributes.Add("onclick", "return ChangeDateRequire('" + panelDuration.ClientID + "','" + panelDateReq.ClientID + "','" + panelDateReqPick.ClientID + "')");
                txtDate.Text = String.Format("{0:dd/MM/yyyy}", DateTime.Today);
                CalendarDate.FocusedDate = DateTime.Today;
                CalendarDate.SelectedDate = DateTime.Today;
                CalendarDateReq.FocusedDate = DateTime.Today;
                CalendarDateReq.SelectedDate = DateTime.Today;
            }
            else
            {
                PurchaseType = Session["PurchaseType"].ToString();
            }
            LoadCommitteeFunctionDetail();
        }

        private void InputItem(string seq, string name, string unit_name)
        {
            IList<PrePurchaseRequestItemInfo> infoListAddPprItem = new List<PrePurchaseRequestItemInfo>();
            BgmExpenseInfo infoExpense = new BgmExpenseInfo();
            BgmSourceInfo infoSource = new BgmSourceInfo();
            ResourceMasterItemInfo infoItem = new ResourceMasterItemInfo();
            MasterUnitInfo infoUnit = new MasterUnitInfo();
            PrePurchaseRequestItemInfo infoPprItem = new PrePurchaseRequestItemInfo();
            MasterPurchaseRuleInfo infoRule = new MasterPurchaseRuleInfo();
            BgmProjectOperationInfo infoOperation = new BgmProjectOperationInfo();
            BgmProjectOperationExpenseInfo infoOperationExpense = new BgmProjectOperationExpenseInfo();
            BgmProjectInfo infoProject = new BgmProjectInfo();
            BgmProjectExpenseInfo infoProjectExpense = new BgmProjectExpenseInfo();
            string[] all_value = seq.Split(new string[] { "-" }, StringSplitOptions.None);
            string[] all_name = name.Split(new string[] { " - " }, StringSplitOptions.None);

            if (ViewState["AddPprItem"] != null)
            {
                infoListAddPprItem = (List<PrePurchaseRequestItemInfo>)ViewState["AddPprItem"];
                foreach (PrePurchaseRequestItemInfo info in infoListAddPprItem)
                {
                    if (info.InfoItem.Seq == Convert.ToInt32(all_value[3]))
                    {
                        return;
                    }
                }
            }
            infoPprItem.Name = all_name[1];
            infoItem.Seq = Convert.ToInt32(all_value[3]);
            infoUnit.Name = unit_name;
            infoSource.Seq = Convert.ToInt32(hdSourceSeq.Value);
            infoSource.Name = hdSourceName.Value;
            infoExpense.Seq = Convert.ToInt32(hdExpenseSeq.Value);
            infoExpense.Name = hdExpenseName.Value;
            if (hdOperationSeq.Value.Length > 0)
            {
                infoOperation.Seq = Convert.ToInt32(hdOperationSeq.Value);
                infoOperation.Name = hdOperationName.Value;
                infoOperationExpense.Seq = Convert.ToInt32(hdOperationExpSeq.Value.ToString());
                infoOperationExpense.InfoOperation = infoOperation;
            }
            else
            {
                infoProject.Seq = Convert.ToInt32(hdProjectSeq.Value);
                infoProject.Name = hdProjectName.Value;
                infoProjectExpense.Seq = Convert.ToInt32(hdProjectExpSeq.Value);
                infoProjectExpense.InfoProject = infoProject;
            }
            infoRule.Seq = Convert.ToInt32(hdRule.Value);
            infoRule.Name = hdRuleName.Value;
            infoItem.InfoUnit = infoUnit;
            infoPprItem.InfoItem = infoItem;
            infoPprItem.InfoSource = infoSource;
            infoPprItem.InfoExpense = infoExpense;
            infoPprItem.InfoProjectExpense = infoProjectExpense;
            infoPprItem.InfoOperationExpense = infoOperationExpense;
            infoPprItem.InfoRule = infoRule;
            infoListAddPprItem.Add(infoPprItem);
            ViewState["AddPprItem"] = infoListAddPprItem;
        }

        protected void LoadDurationType()
        {
            IList<SysDurationTypeInfo> infoList = bllDurationType.GetSysDurationType();
            cbDurationType.DataSource = infoList;
            cbDurationType.DataBind();
        }

        protected void LoadDurationCount()
        {
            IList<SysDurationCountInfo> infoList = bllDurationCount.GetSysDurationCount();
            cbDurationCount.DataSource = infoList;
            cbDurationCount.DataBind();
        }

        protected void LoadCommitteeFunction(int map_seq)
        {
            IList<MasterCommitteeFunctionInfo> infoList = bllComFunction.GetMasterCommitteeFunctionWithMapping(map_seq);
            cblCommitteeFunction.DataSource = infoList;
            cblCommitteeFunction.DataBind();
            for (int i = 0; i < cblCommitteeFunction.Items.Count; i++)
            {
                cblCommitteeFunction.Items[i].Selected = true;
            }
            cblCommitteeFunction.Attributes["onclick"] = "return false;";
            tableNumCommitteeFunction.Controls.Clear();
            LoadCommitteeFunctionDetail();
        }

        public void LoadCommitteeFunctionDetail()
        {
            for (int i = 0; i < cblCommitteeFunction.Items.Count; i++)
            {
                TableRow tr = new TableRow();
                TableCell td = new TableCell();
                RadNumericTextBox txt = new RadNumericTextBox();
                txt.ID = "txtFunction_" + cblCommitteeFunction.Items[i].Value;
                txt.Text = "1";
                txt.Width = Unit.Pixel(30);
                //txt.CssClass = "RadNumericTextBox";
                txt.Skin = "Outlook";
                txt.NumberFormat.DecimalDigits = 0;
                Label lbl = new Label();
                lbl.Text = " ชุด";
                td.VerticalAlign = VerticalAlign.Top;
                td.Controls.Add(txt);
                td.Controls.Add(lbl);
                tr.Cells.Add(td);
                tableNumCommitteeFunction.Rows.Add(tr);
            }
        }

        protected void LoadCommitteeFunction()
        {
            IList<MasterCommitteeFunctionInfo> infoList = bllComFunction.GetMasterCommitteeFunction();
            cbCommitteeFunction.DataSource = infoList;
            cbCommitteeFunction.DataBind();
        }

        protected void LoadCommitteePosition()
        {
            IList<MasterCommitteePositionInfo> infoList = bllComPosition.GetMasterCommitteePosition();
            cbCommitteePosition.DataSource = infoList;
            cbCommitteePosition.DataBind();
        }

        protected void LoadOperationTree()
        {
            IList<TreeInfo> info = bllTree.GetBgmExpenseProjectOperation(Convert.ToInt32(txtYear.Text), Convert.ToInt32(cbJobSite.SelectedValue));
            RadTreeView tree = (RadTreeView)cbOperation.Items[0].FindControl("TreeViewOperation");

            tree.DataSource = info;
            tree.DataBind();
        }

        protected void LoadProjectTree()
        {
            IList<TreeInfo> info = bllTree.GetBgmExpenseProject(Convert.ToInt32(txtYear.Text), Convert.ToInt32(cbJobSite.SelectedValue));
            RadTreeView tree = (RadTreeView)cbProject.Items[0].FindControl("TreeViewProject");

            tree.DataSource = info;
            tree.DataBind();
        }

        protected void LoadGridSubItem()
        {
            IList<PrePurchaseRequestItemInfo> infoListAddPprItem = new List<PrePurchaseRequestItemInfo>();
            if (ViewState["AddPprItem"] != null)
            {
                infoListAddPprItem = (List<PrePurchaseRequestItemInfo>)ViewState["AddPprItem"];
            }
            Grid_SubItem.DataSource = infoListAddPprItem;
            Grid_SubItem.DataBind();
        }

        protected void LoadGridItem()
        {
            IList<PrePurchaseRequestItemInfo> infoListPprItem = new List<PrePurchaseRequestItemInfo>();
            if (ViewState["PprItem"] != null)
            {
                infoListPprItem = (List<PrePurchaseRequestItemInfo>)ViewState["PprItem"];
            }
            Grid_Item.DataSource = infoListPprItem;
            GridGroupByExpression geSource = new GridGroupByExpression(Grid_Item.Columns[1]);
            GridGroupByExpression geExpense = new GridGroupByExpression(Grid_Item.Columns[2]);
            GridGroupByExpression geRule = new GridGroupByExpression(Grid_Item.Columns[3]);
            GridGroupByExpression geOperation = new GridGroupByExpression(Grid_Item.Columns[4]);
            GridGroupByExpression geProject = new GridGroupByExpression(Grid_Item.Columns[5]);


            UseMethod = Session["UseMethod"].ToString();

            Grid_Item.MasterTableView.GroupByExpressions.Add(geRule);
            //Grid_Item.MasterTableView.GroupByExpressions.Add(geSource);
            if (UseMethod == "1") //ใช้เงินผ่านรายการปกติ
            {
                Grid_Item.MasterTableView.GroupByExpressions.Add(geProject);
            }
            else //ใช้เงินผ่านโครงการบูรณาการ
            {
                Grid_Item.MasterTableView.GroupByExpressions.Add(geOperation);
            }
            
            Grid_Item.MasterTableView.GroupByExpressions.Add(geExpense);
            Grid_Item.DataBind();
            if (infoListPprItem.Count == 0)
            {
                ViewState["Rule"] = null;
            }
           
            cmdFac.GridCommand(panelList_Item, panelGrid_Item, panelCommand_Item);
        }

        protected void LoadGridFile()
        {
            IList<DocumentInfo> infoListFile = new List<DocumentInfo>();
            if (ViewState["File"] != null)
            {
                infoListFile = (List<DocumentInfo>)ViewState["File"];
            }
            Grid_File.DataSource = infoListFile;
            Grid_File.DataBind();

            cmdFac.GridCommand(panelList_File, panelGrid_File, panelCommand_File);
        }

        protected void LoadGridSubCommittee()
        {
            IList<PrePurchaseRequestCommitteeInfo> infoListAddCommittee = new List<PrePurchaseRequestCommitteeInfo>();
            if (ViewState["AddCommittee"] != null)
            {
                infoListAddCommittee = (List<PrePurchaseRequestCommitteeInfo>)ViewState["AddCommittee"];
            }
            Grid_SubCommittee.DataSource = infoListAddCommittee;
            GridGroupByExpression geFunction = new GridGroupByExpression(Grid_SubCommittee.Columns[0]);
            GridGroupByExpression geRefNo = new GridGroupByExpression(Grid_SubCommittee.Columns[1]);
            Grid_SubCommittee.MasterTableView.GroupByExpressions.Add(geFunction);
            Grid_SubCommittee.MasterTableView.GroupByExpressions.Add(geRefNo);
            Grid_SubCommittee.DataBind();
        }

        protected void LoadGridCommittee()
        {
            IList<PrePurchaseRequestCommitteeInfo> infoListCommittee = new List<PrePurchaseRequestCommitteeInfo>();
            if (ViewState["Committee"] != null)
            {
                infoListCommittee = (List<PrePurchaseRequestCommitteeInfo>)ViewState["Committee"];
            }
            Grid_Committee.DataSource = infoListCommittee;
            GridGroupByExpression geFunction = new GridGroupByExpression(Grid_Committee.Columns[1]);
            GridGroupByExpression geRefNo = new GridGroupByExpression(Grid_Committee.Columns[2]);
            Grid_Committee.MasterTableView.GroupByExpressions.Add(geFunction);
            Grid_Committee.MasterTableView.GroupByExpressions.Add(geRefNo);
            Grid_Committee.DataBind();

            cmdFac.GridCommand(panelList_Committee, panelGrid_Committee, panelCommand_Committee);
        }

        protected void cbJobSite_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            IList<HrmJobSiteInfo> infoList = bllJobSite.GetJobSite(e.Text);
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + ItemsPerRequest, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cbJobSite.Items.Add(new RadComboBoxItem(infoList[i].Name, infoList[i].Seq.ToString()));
                TableRow tr = new TableRow();
                TableCell tdScopeName = new TableCell();
                Label lblScopeName = new Label();
                lblScopeName.Text = infoList[i].InfoScope.Name;
                tdScopeName.Width = Unit.Pixel(100);
                tdScopeName.Controls.Add(lblScopeName);
                tr.Cells.Add(tdScopeName);

                TableCell tdJobSite = new TableCell();
                Label lblJobSite = new Label();
                lblJobSite.Text = infoList[i].Name;
                tdJobSite.Width = Unit.Pixel(500);
                tdJobSite.Controls.Add(lblJobSite);
                tr.Cells.Add(tdJobSite);

                ((Table)cbJobSite.Items[j].FindControl("tableJobSite")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }

        protected void TreeItem_NodeExpand(object sender, RadTreeNodeEventArgs e)
        {
            PopulateNodeOnDemand(e, TreeNodeExpandMode.ServerSideCallBack);
        }

        private static void LoadRootNodes(RadTreeView treeView, TreeNodeExpandMode expandMode)
        {
            IBLLTree bll = new TreeBLL();

            foreach (TreeInfo info in bll.GetResourceMasterTreeWithoutHeader(""))
            {
                RadTreeNode node = new RadTreeNode();
                node.Text = info.Name;
                node.ToolTip = info.Descr;
                node.Value = info.Id;
                node.ImageUrl = info.Image_url;
                node.Checkable = false;
                if (Convert.ToInt32(info.Children_count) > 0)
                {
                    node.ExpandMode = expandMode;
                }
                treeView.Nodes.Add(node);
            }
        }

        private static void PopulateNodeOnDemand(RadTreeNodeEventArgs e, TreeNodeExpandMode expandMode)
        {
            e.Node.Dispose();
            e.Node.Nodes.Clear();
            IBLLTree bll = new TreeBLL();
            foreach (TreeInfo info in bll.GetResourceMasterTreeWithoutHeader(e.Node.Value))
            {
                RadTreeNode node = new RadTreeNode();
                node.Text = info.Name;
                node.ToolTip = info.Descr;
                node.Value = info.Id;
                node.ImageUrl = info.Image_url;
                node.Checkable = (info.Category == "ITEM");
                if (Convert.ToInt32(info.Children_count) > 0)
                {
                    node.ExpandMode = expandMode;
                }
                e.Node.Nodes.Add(node);
            }

            e.Node.Expanded = true;
            e.Node.ExpandMode = expandMode;
        }

        protected void btnSelectItem_Click(object sender, EventArgs e)
        {
            foreach (RadTreeNode node in TreeItem.GetAllNodes())
            {
                if (node.Checkable && node.Checked)
                {
                    InputItem(node.Value, node.Text, node.ToolTip);
                }
            }
            LoadGridSubItem();
        }

        protected void btnDeleteItem_Click(object sender, EventArgs e)
        {
            int[] data_value = new int[Grid_SubItem.MasterTableView.GetSelectedItems().Length];
            int item = Grid_SubItem.MasterTableView.GetSelectedItems().Length;
            foreach (GridDataItem data in Grid_SubItem.MasterTableView.GetSelectedItems())
            {
                item = item - 1;
                data_value[item] = data.ItemIndex;
            }

            for (int i = 0; i < data_value.Length; i++)
            {
                ((List<PrePurchaseRequestItemInfo>)ViewState["AddPprItem"]).RemoveAt(data_value[i]);
            }

            LoadGridSubItem();
        }

        protected void nextButton_Detail_Click(object sender, EventArgs e)
        {
            string strJobSite = "";
            string strYear = "";
            RadManager1.ResponseScripts.Add(@"ChangeTab('Item',1);");
            if (ViewState["JobSite"] != null)
            {
                strJobSite = ViewState["JobSite"].ToString();
            }
            if (ViewState["Year"] != null)
            {
                strYear = ViewState["Year"].ToString();
            }
            if (cbJobSite.SelectedValue != strJobSite || txtYear.Text != strYear)
            {
                LoadProjectTree();
                LoadOperationTree();
                SetViewStateJobSite(cbJobSite.SelectedValue);
                SetViewStateYear(txtYear.Text);
            }
        }

        protected void backButton_Item_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Detail',0);");
        }

        protected void nextButton_Item_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Committee',2);");
        }

        protected void backButton_Committee_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Item',1);");
        }

        protected void nextButton_Committee_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('File',3);");
        }

        protected void backButton_File_Click(object sender, EventArgs e)
        {
            RadManager1.ResponseScripts.Add(@"ChangeTab('Committee',2);");
        }

        protected void finishButton_File_Click(object sender, EventArgs e)
        {
            PrePurchaseRequestInfo info = new PrePurchaseRequestInfo();
            SysYearTypeInfo infoYearType = new SysYearTypeInfo();
            HrmJobSiteInfo infoJobSiteRequest = new HrmJobSiteInfo();
            HrmJobSiteInfo infoJobSite = new HrmJobSiteInfo();
            HrmJobSiteInfo infoJobSiteDirect = new HrmJobSiteInfo();
            HrmEmployeeInfo infoEmployee = new HrmEmployeeInfo();
            MasterPurchaseTypeInfo infoPurchaseType = new MasterPurchaseTypeInfo();
            SysPprForInfo infoFor = new SysPprForInfo();
            SysPprTypeInfo infoPprType = new SysPprTypeInfo();
            SysPprUseMethodInfo infoUseMethod = new SysPprUseMethodInfo();
            SysDurationTypeInfo infoDurationType = new SysDurationTypeInfo();
            SysDurationCountInfo infoDurationCount = new SysDurationCountInfo();
            RecordInfo infoRecord = new RecordInfo();
            string lastNumber = "";
            IList<PrePurchaseRequestItemInfo> infoListItem = new List<PrePurchaseRequestItemInfo>();
            IList<PrePurchaseRequestCommitteeInfo> infoListCommittee = new List<PrePurchaseRequestCommitteeInfo>();
            IList<DocumentInfo> infoListFile = new List<DocumentInfo>();
            if (ViewState["PprItem"] != null)
            {
                infoListItem = (List<PrePurchaseRequestItemInfo>)ViewState["PprItem"];
            }
            if (ViewState["Committee"] != null)
            {
                infoListCommittee = (List<PrePurchaseRequestCommitteeInfo>)ViewState["Committee"];
            }
            if (ViewState["File"] != null)
            {
                infoListFile = (List<DocumentInfo>)ViewState["File"];
            }

            infoYearType.Seq = Convert.ToInt32(cbYearType.SelectedValue);
            info.Year = Convert.ToInt32(txtYear.Text);

            //ต้องรอแก้ไข
            //RadTreeView JobSitetree = (RadTreeView)this.cbJobSite.Items[0].FindControl("TreeViewJobSite");
            //string[] seq = JobSitetree.SelectedValue.ToString().Split('-');
            string[] jobsite_value = bllPersonal.GetUserJobSite(Convert.ToInt32(Session["EmpSeq"].ToString()));
            infoJobSiteRequest.Seq = Convert.ToInt32(cbJobSite.SelectedValue);
            infoJobSite.Seq = Convert.ToInt32(cbJobSite.SelectedValue);
            infoJobSiteDirect.Seq = Convert.ToInt32(cbJobSite.SelectedValue);

            infoEmployee.Seq = Convert.ToInt32(Session["EmpSeq"].ToString());
            info.DateRequested = Convert.ToDateTime(txtDate.TextWithLiterals);
            infoPurchaseType.Seq = Convert.ToInt32(this.PurchaseType);
            info.Name = txtName.Text;
            info.Reason = txtReason.Text;
            infoFor.Seq = Convert.ToInt32(rbFor.SelectedValue);
            infoPprType.Seq = 1; //จัดหาผ่านกระบวนการพัสดุมาตรฐาน
            if (rdbDuration.Checked)
            {
                if (txtDurationReq.Text.Length > 0)
                {
                    info.DurationRequired = Convert.ToInt32(txtDurationReq.Value);
                    infoDurationType.Seq = Convert.ToInt32(cbDurationType.SelectedValue);
                    infoDurationCount.Seq = Convert.ToInt32(cbDurationCount.SelectedValue);
                }
            }
            if (rdbDate.Checked)
            {
                if (txtDateReq.Text.Length > 0)
                {
                    info.DateRequired = Convert.ToDateTime(txtDateReq.TextWithLiterals);
                }
            }

            infoRecord.Created_by = cn.UserID;
            infoRecord.Created_when = DateTime.Now;
            info.InfoEmployeeRequest = infoEmployee;
            info.InfoPurchaseType = infoPurchaseType;
            info.InfoDurationCount = infoDurationCount;
            info.InfoDurationType = infoDurationType;
            info.InfoJobSite = infoJobSite;
            info.InfoJobSiteDirect = infoJobSiteDirect;
            info.InfoJobSiteRequest = infoJobSiteRequest;
            info.InfoPprFor = infoFor;
            infoUseMethod.Seq = Convert.ToInt32(Request.QueryString["um"]);
            info.InfoPprUseMethod = infoUseMethod;
            info.InfoPprType = infoPprType;
            info.InfoYearType = infoYearType;
            info.InfoRecord = infoRecord;

            try
            {
                lastNumber = bll.Insert(info, infoListItem, infoListCommittee, infoListFile);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }

            RadManager1.Alert("เลขที่รายการของท่านคือ : '" + lastNumber + "'");
            RadManager1.ResponseScripts.Add(@"CloseWindow();");
        }

        protected void RadManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            IList<PrePurchaseRequestItemInfo> infoListAddPprItem = new List<PrePurchaseRequestItemInfo>();
            string[] all_value = e.Argument.Split(new string[] { " : " }, StringSplitOptions.None);
            if (all_value[0] == "Project")
            {
                ViewState["AddPprItem"] = null;
                string[] data_value = all_value[1].Split(new string[] { "-" }, StringSplitOptions.None);
                hdRule.Value = data_value[0];
                hdProjectSeq.Value = data_value[2];
                hdProjectExpSeq.Value = data_value[3];
                BgmProjectExpenseInfo infoProjectExpense = bllProjectExpense.GetBgmProjectExpense(Convert.ToInt32(data_value[3]));
                MasterPurchaseRuleInfo infoRule = bllRule.GetMasterPurchaseRule(Convert.ToInt32(data_value[0]));
                BgmProjectInfo infoProject = bllProject.GetBgmProject(Convert.ToInt32(data_value[2]));
                udPanelItem.Visible = true;
                lblAllBudget.Text = Convert.ToDouble(infoProjectExpense.Price).ToString("###,###,##0.00");
                lblRemainBudget.Text = Convert.ToDouble(infoProjectExpense.Price).ToString("###,###,##0.00");
                if (infoProjectExpense.InfoItem.Seq != null) //เป็นค่าครุภัณฑ์ ที่ดิน สิ่งก่อสร้าง
                {
                    panelAddItem.Visible = false;
                    Grid_SubItem.Columns[0].Visible = false;
                    BgmSourceInfo infoSource = new BgmSourceInfo();
                    BgmExpenseInfo infoExpense = new BgmExpenseInfo();
                    ResourceMasterItemInfo infoItem = new ResourceMasterItemInfo();
                    MasterUnitInfo infoUnit = new MasterUnitInfo();
                    PrePurchaseRequestItemInfo infoPprItem = new PrePurchaseRequestItemInfo();
                    infoSource.Seq = infoProjectExpense.InfoSource.Seq;
                    infoSource.Name = infoProjectExpense.InfoSource.Name;
                    infoPprItem.Name = infoProjectExpense.InfoItem.Name;
                    infoPprItem.Qty = infoProjectExpense.Qty;
                    infoPprItem.Price = infoProjectExpense.Price;
                    infoExpense.Seq = infoProjectExpense.InfoExpense.Seq;
                    infoExpense.Name = infoProjectExpense.InfoExpense.Name;
                    infoItem.Seq = infoProjectExpense.InfoItem.Seq;
                    infoUnit.Name = infoProjectExpense.InfoItem.InfoUnit.Name;
                    infoItem.InfoUnit = infoUnit;
                    infoPprItem.InfoItem = infoItem;
                    infoPprItem.InfoExpense = infoExpense;
                    infoPprItem.InfoSource = infoSource;
                    infoPprItem.InfoRule = infoRule;

                    infoPprItem.InfoProjectExpense = infoProjectExpense;

                    infoListAddPprItem.Add(infoPprItem);
                    ViewState["AddPprItem"] = infoListAddPprItem;
                }
                else if (infoProjectExpense.InfoExpense.Name.IndexOf("วัสดุ") >= 0) // เป็นค่าวัสดุ
                {
                    hdSourceSeq.Value = infoProjectExpense.InfoSource.Seq.ToString();
                    hdSourceName.Value = infoProjectExpense.InfoSource.Name;
                    hdExpenseSeq.Value = infoProjectExpense.InfoExpense.Seq.ToString();
                    hdExpenseName.Value = infoProjectExpense.InfoExpense.Name;
                    hdRule.Value = infoRule.Seq.ToString();
                    hdRuleName.Value = infoRule.Name;
                    hdProjectSeq.Value = infoProject.Seq.ToString();
                    hdProjectName.Value = infoProject.Name;
                    panelAddItem.Visible = true;
                    
                    Grid_SubItem.Columns[0].Visible = true;
                    ViewState["AddPprItem"] = infoListAddPprItem;
                }
                else //เป็นรายจ่ายอื่นๆ เช่น ค่าจ้างเหมาบริการ 
                {
                    panelAddItem.Visible = false;
                    Grid_SubItem.Columns[0].Visible = false;
                    BgmSourceInfo infoSource = new BgmSourceInfo();
                    BgmExpenseInfo infoExpense = new BgmExpenseInfo();
                    ResourceMasterItemInfo infoItem = new ResourceMasterItemInfo();
                    MasterUnitInfo infoUnit = new MasterUnitInfo();
                    PrePurchaseRequestItemInfo infoPprItem = new PrePurchaseRequestItemInfo();
                    infoSource.Seq = infoProjectExpense.InfoSource.Seq;
                    infoSource.Name = infoProjectExpense.InfoSource.Name;
                    infoPprItem.Name = infoProjectExpense.InfoExpense.Name;
                    infoPprItem.Qty = (infoProjectExpense.Qty.ToString().Length == 0 ? 1 : infoProjectExpense.Qty);
                    infoPprItem.Price = infoProjectExpense.Price;
                    infoExpense.Seq = infoProjectExpense.InfoExpense.Seq;
                    infoExpense.Name = infoProjectExpense.InfoExpense.Name;
                    infoUnit.Name = "รายการ";
                    infoItem.InfoUnit = infoUnit;
                    infoPprItem.InfoItem = infoItem;
                    infoPprItem.InfoExpense = infoExpense;
                    infoPprItem.InfoSource = infoSource;
                    infoPprItem.InfoRule = infoRule;

                    infoPprItem.InfoProjectExpense = infoProjectExpense;

                    infoListAddPprItem.Add(infoPprItem);
                    ViewState["AddPprItem"] = infoListAddPprItem;
                }
            }
            if (all_value[0] == "Operation")
            {
                ViewState["AddPprItem"] = null;
                string[] data_value = all_value[1].Split(new string[] { "-" }, StringSplitOptions.None);
                hdRule.Value = data_value[0];
                hdOperationSeq.Value = data_value[2];
                hdOperationExpSeq.Value = data_value[3];
                BgmProjectOperationExpenseInfo infoOperationExpense = bllOperationExpense.GetBgmProjectOperationExpense(Convert.ToInt32(data_value[3]));
                MasterPurchaseRuleInfo infoRule = bllRule.GetMasterPurchaseRule(Convert.ToInt32(data_value[0]));
                BgmProjectOperationInfo infoOperation = bllOperation.GetBgmProjectOperation(Convert.ToInt32(data_value[2]));
                udPanelItem.Visible = true;
                lblAllBudget.Text = Convert.ToDouble(infoOperationExpense.Price).ToString("###,###,##0.00");
                lblRemainBudget.Text = Convert.ToDouble(infoOperationExpense.Price).ToString("###,###,##0.00");
                if (infoOperationExpense.InfoItem.Seq != null) //เป็นค่าครุภัณฑ์ ที่ดิน สิ่งก่อสร้าง
                {
                    panelAddItem.Visible = false;
                    Grid_SubItem.Columns[0].Visible = false;
                    BgmSourceInfo infoSource = new BgmSourceInfo();
                    BgmExpenseInfo infoExpense = new BgmExpenseInfo();
                    ResourceMasterItemInfo infoItem = new ResourceMasterItemInfo();
                    MasterUnitInfo infoUnit = new MasterUnitInfo();
                    PrePurchaseRequestItemInfo infoPprItem = new PrePurchaseRequestItemInfo();
                    infoSource.Seq = infoOperationExpense.InfoSource.Seq;
                    infoSource.Name = infoOperationExpense.InfoSource.Name;
                    infoPprItem.Name = infoOperationExpense.InfoItem.Name;
                    infoPprItem.Qty = infoOperationExpense.Qty;
                    infoPprItem.Price = infoOperationExpense.Price;
                    infoExpense.Seq = infoOperationExpense.InfoExpense.Seq;
                    infoExpense.Name = infoOperationExpense.InfoExpense.Name;
                    infoItem.Seq = infoOperationExpense.InfoItem.Seq;
                    infoUnit.Name = infoOperationExpense.InfoItem.InfoUnit.Name;
                    infoItem.InfoUnit = infoUnit;
                    infoPprItem.InfoItem = infoItem;
                    infoPprItem.InfoExpense = infoExpense;
                    infoPprItem.InfoSource = infoSource;
                    infoPprItem.InfoRule = infoRule;

                    infoPprItem.InfoOperationExpense= infoOperationExpense;

                    infoListAddPprItem.Add(infoPprItem);
                    ViewState["AddPprItem"] = infoListAddPprItem;
                }
                else if (infoOperationExpense.InfoExpense.Name.IndexOf("วัสดุ") >= 0) // เป็นค่าวัสดุ
                {
                    hdSourceSeq.Value = infoOperationExpense.InfoSource.Seq.ToString();
                    hdSourceName.Value = infoOperationExpense.InfoSource.Name;
                    hdExpenseSeq.Value = infoOperationExpense.InfoExpense.Seq.ToString();
                    hdExpenseName.Value = infoOperationExpense.InfoExpense.Name;
                    hdRule.Value = infoRule.Seq.ToString();
                    hdRuleName.Value = infoRule.Name;
                    hdOperationSeq.Value = infoOperation.Seq.ToString();
                    hdOperationName.Value = infoOperation.Name;
                    panelAddItem.Visible = true;
                    Grid_SubItem.Columns[0].Visible = true;
                    ViewState["AddPprItem"] = infoListAddPprItem;
                }
                else //เป็นรายจ่ายอื่นๆ เช่น ค่าจ้างเหมาบริการ 
                {
                    panelAddItem.Visible = false;
                    Grid_SubItem.Columns[0].Visible = false;
                    BgmSourceInfo infoSource = new BgmSourceInfo();
                    BgmExpenseInfo infoExpense = new BgmExpenseInfo();
                    ResourceMasterItemInfo infoItem = new ResourceMasterItemInfo();
                    MasterUnitInfo infoUnit = new MasterUnitInfo();
                    PrePurchaseRequestItemInfo infoPprItem = new PrePurchaseRequestItemInfo();
                    infoSource.Seq = infoOperationExpense.InfoSource.Seq;
                    infoSource.Name = infoOperationExpense.InfoSource.Name;
                    infoPprItem.Name = infoOperationExpense.InfoExpense.Name;
                    infoPprItem.Qty = (infoOperationExpense.Qty.ToString().Length == 0 ? 1 : infoOperationExpense.Qty); ;
                    infoPprItem.Price = infoOperationExpense.Price;
                    infoExpense.Seq = infoOperationExpense.InfoExpense.Seq;
                    infoExpense.Name = infoOperationExpense.InfoExpense.Name;
                    infoUnit.Name = "รายการ";
                    infoItem.InfoUnit = infoUnit;
                    infoPprItem.InfoItem = infoItem;
                    infoPprItem.InfoExpense = infoExpense;
                    infoPprItem.InfoSource = infoSource;
                    infoPprItem.InfoRule = infoRule;

                    infoPprItem.InfoOperationExpense = infoOperationExpense;

                    infoListAddPprItem.Add(infoPprItem);
                    ViewState["AddPprItem"] = infoListAddPprItem;
                }
            }

            if (panelAddItem.Visible)
                LoadRootNodes(TreeItem, TreeNodeExpandMode.ServerSideCallBack);

            LoadGridSubItem();

            foreach (GridDataItem data in Grid_SubItem.MasterTableView.Items)
            {
                ((RadNumericTextBox)data["Qty"].FindControl("txtQty")).Enabled = false;
            }

        }

        protected void ShowGrid_Item_Click(object sender, EventArgs e)
        {
            cbProject.SelectedIndex = 0;
            cbOperation.SelectedIndex = 0;
            udPanelItem.Visible = false;
            ViewState["AddPprItem"] = null;
            LoadGridItem();
        }

        protected void AddNew_Item_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList_Item, panelGrid_Item, panelCommand_Item);
            LoadValidateItem();
        }

        protected void AddNewSave_Item_Click(object sender, EventArgs e)
        {
            IList<PrePurchaseRequestItemInfo> infoListPprItem = new List<PrePurchaseRequestItemInfo>();
            IList<PrePurchaseRequestItemInfo> infoTempPprItem = new List<PrePurchaseRequestItemInfo>();
            if (ViewState["PprItem"] != null)
            {
                infoListPprItem = (List<PrePurchaseRequestItemInfo>)ViewState["PprItem"];
            }
            if (Grid_SubItem.MasterTableView.Items.Count == 0)
            {
                RadManager1.Alert("กรุณาเลือกรายการพัสดุ");
                return;
            }
            else
            {
                if (ViewState["Rule"] != null)
                {
                    if (ViewState["Rule"].ToString() != hdRule.Value)
                    {
                        RadManager1.Alert("แผนการใช้จ่ายงบประมาณต้องอยู่ภายใต้ระเบียบการจัดหาเดียวกันเท่านั้น");
                        return;
                    }
                }

                foreach (GridDataItem data in Grid_SubItem.MasterTableView.Items)
                {
                    BgmSourceInfo infoSource = new BgmSourceInfo();
                    BgmExpenseInfo infoExpense = new BgmExpenseInfo();
                    PrePurchaseRequestItemInfo info = new PrePurchaseRequestItemInfo();
                    MasterUnitInfo infoUnit = new MasterUnitInfo();
                    ResourceMasterItemInfo infoItem = new ResourceMasterItemInfo();
                    MasterPurchaseRuleInfo infoRule = new MasterPurchaseRuleInfo();
                    BgmProjectInfo infoProject = new BgmProjectInfo();
                    BgmProjectExpenseInfo infoProjectExpense = new BgmProjectExpenseInfo();
                    BgmProjectOperationInfo infoOperation = new BgmProjectOperationInfo();
                    BgmProjectOperationExpenseInfo infoOperationExpense = new BgmProjectOperationExpenseInfo();
                    RecordInfo infoRecord = new RecordInfo();
                    string item_seq = data["InfoItem.Seq"].Text;
                    string source_seq = data["InfoSource.Seq"].Text;
                    string source_name = data["InfoSource.Name"].Text;
                    string expense_seq = data["InfoExpense.Seq"].Text;
                    string expense_name = data["InfoExpense.Name"].Text;
                    string oper_seq = data["InfoOperationExpense.InfoOperation.Seq"].Text;
                    string oper_name = data["InfoOperationExpense.InfoOperation.Name"].Text;
                    string proj_seq = data["InfoProjectExpense.InfoProject.Seq"].Text;
                    string proj_name = data["InfoProjectExpense.InfoProject.Name"].Text;
                    string rule_seq = data["InfoRule.Seq"].Text;
                    string rule_name = data["InfoRule.Name"].Text;
                    string oper_exp_seq = data["InfoOperationExpense.seq"].Text;
                    string pro_exp_seq = data["InfoProjectExpense.seq"].Text;
                    string name = ((HyperLink)data["Name"].FindControl("lkName")).Text;
                    string descr = ((TextBox)data["Descr"].FindControl("txtDescr")).Text;
                    string qty = ((RadNumericTextBox)data["Qty"].FindControl("txtQty")).Value.ToString();
                    string price = ((RadNumericTextBox)data["Price"].FindControl("txtPrice")).Value.ToString();
                    string unit_name = data["InfoItem.InfoUnit.Name"].Text;
                    info.Name = name;
                    info.Descr = descr;
                    //if (qty.Length == 0 || price.Length == 0)
                    //{
                    //    RadManager1.Alert("กรุณาระบุจำนวนและราคาประมาณการต่อหน่วยให้ครบถ้วน");
                    //    return;
                    //}
                    if (qty.Length == 0)
                    {
                        RadManager1.Alert("กรุณาระบุจำนวนที่ต้องการให้ครบถ้วน");
                        return;
                    }
                    info.Qty = Convert.ToInt32(qty);
                    info.Price = (price.Length > 0 ? Convert.ToDouble(price) : 0);
                    infoUnit.Name = unit_name;
                    if (item_seq.Replace("&nbsp;","").Length > 0)
                    {
                        infoItem.Seq = Convert.ToInt32(item_seq);
                    }
                    infoExpense.Seq = Convert.ToInt32(expense_seq);
                    infoExpense.Name = expense_name;
                    infoSource.Seq = Convert.ToInt32(source_seq);
                    infoSource.Name = source_name;
                    infoRule.Seq = Convert.ToInt32(rule_seq);
                    infoRule.Name = rule_name;
                    infoRecord.Created_by = cn.UserID;
                    infoRecord.Created_when = DateTime.Now;
                    infoItem.InfoUnit = infoUnit;
                    info.InfoSource = infoSource;
                    info.InfoExpense = infoExpense;
                    info.InfoItem = infoItem;
                    info.InfoRecord = infoRecord;
                    info.InfoRule = infoRule;
                    if (proj_seq.Replace("&nbsp;", "").ToString().Length > 0)
                    {
                        infoProject.Seq = Convert.ToInt32(proj_seq);
                        infoProject.Name = proj_name.Replace("&nbsp;", "");
                        infoProjectExpense.Seq = Convert.ToInt32(pro_exp_seq.Replace("&nbsp;", ""));
                        infoProjectExpense.InfoProject = infoProject;
                        info.InfoProjectExpense = infoProjectExpense;
                    }
                    if (oper_seq.Replace("&nbsp;", "").ToString().Length > 0)
                    {
                        infoOperation.Seq = Convert.ToInt32(oper_seq);
                        infoOperation.Name = oper_name.Replace("&nbsp;", "");
                        infoOperationExpense.Seq = Convert.ToInt32(oper_exp_seq.Replace("&nbsp;", ""));
                        infoOperationExpense.InfoOperation = infoOperation;
                        info.InfoOperationExpense = infoOperationExpense;
                    }
                    infoTempPprItem.Add(info);
                }

                for (int i = 0; i < infoTempPprItem.Count; i++)
                {
                    infoListPprItem.Add(infoTempPprItem[i]);
                }
                ViewState["PprItem"] = infoListPprItem;
                ViewState["Rule"] = hdRule.Value;
                cbProject.SelectedIndex = 0;
                cbOperation.SelectedIndex = 0;
                udPanelItem.Visible = false;
                TreeItem.ClearCheckedNodes();
                LoadGridItem();
            }
        }

        protected void Delete_Item_Click(object sender, EventArgs e)
        {
            int[] data_value = new int[Grid_Item.MasterTableView.GetSelectedItems().Length];
            int item = Grid_Item.MasterTableView.GetSelectedItems().Length;
            foreach (GridDataItem data in Grid_Item.MasterTableView.GetSelectedItems())
            {
                item = item - 1;
                data_value[item] = data.ItemIndex;
            }

            for (int i = 0; i < data_value.Length; i++)
            {
                ((List<PrePurchaseRequestItemInfo>)ViewState["PprItem"]).RemoveAt(data_value[i]);
            }

            LoadGridItem();
        }

        protected void ShowGrid_Committee_Click(object sender, EventArgs e)
        {
            LoadGridCommittee();
        }

        protected void AddNew_Committee_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList_Committee, panelGrid_Committee, panelCommand_Committee);
            panelAddCommittee_Normal.Visible = false;
            panelAddCommittee_Wizard.Visible = true;
        }

        protected void AddNewSave_Committee_Click(object sender, EventArgs e)
        {
            IList<PrePurchaseRequestCommitteeInfo> infoListCommittee = new List<PrePurchaseRequestCommitteeInfo>();
            IList<PrePurchaseRequestCommitteeInfo> infoTempCommittee = new List<PrePurchaseRequestCommitteeInfo>();
            if (ViewState["Committee"] != null)
            {
                infoListCommittee = (List<PrePurchaseRequestCommitteeInfo>)ViewState["Committee"];
            }
            if (panelAddCommittee_Normal.Visible) //เพิ่มด้วยวิธีปกติ
            {
                PrePurchaseRequestCommitteeInfo info = new PrePurchaseRequestCommitteeInfo();
                HrmEmployeeInfo infoEmployee = new HrmEmployeeInfo();
                MasterCommitteePositionInfo infoPosition = new MasterCommitteePositionInfo();
                MasterCommitteeFunctionInfo infoFunction = new MasterCommitteeFunctionInfo();
                HrmEmployeeInfo infoEmployeeDetail = new HrmEmployeeInfo();
                SysCommitteeTypeInfo infoType = new SysCommitteeTypeInfo();
                RecordInfo infoRecord = new RecordInfo();
                info.Ref_no = Convert.ToInt32(txtCommitteeRefno.Value);
                infoType.Seq = Convert.ToInt32(rblCommitteeType.SelectedValue);
                infoType.Name = (rblCommitteeType.SelectedItem.Text);
                infoPosition.Seq = Convert.ToInt32(cbCommitteePosition.SelectedValue);
                infoPosition.Name = cbCommitteePosition.SelectedItem.Text;
                infoFunction.Seq = Convert.ToInt32(cbCommitteeFunction.SelectedValue);
                infoFunction.Name = cbCommitteeFunction.SelectedItem.Text;
                if (infoType.Seq == 1) //เป็นบุคลากรภายใน
                {
                    infoEmployee.Seq = Convert.ToInt32(cbCommitteeInternalName.SelectedValue);
                    infoEmployee.Name = cbCommitteeInternalName.Text;
                    infoEmployeeDetail = bllEmployee.GetHrmEmployee(Convert.ToInt32(infoEmployee.Seq));
                    info.Name = infoEmployee.Name;
                    info.Descr = (infoEmployeeDetail.InfoJobSite.Name.Length > 0 ? " <b>หน่วยงาน : </b>" + infoEmployeeDetail.InfoJobSite.Name : "")
                        + (infoEmployeeDetail.InfoPosition.Name.Length > 0 ? " <b>ตำแหน่ง :</b>" + infoEmployeeDetail.InfoPosition.Name : "")
                        + (infoEmployeeDetail.InfoClass.Name.Length > 0 ? " <b>ระดับ :</b>" + infoEmployeeDetail.InfoClass.Name : "");
                }
                else
                {
                    info.Ex_name = txtCommitteeExternalName.Text;
                    info.Ex_descr = txtCommitteeExternalDescr.Text;
                    info.Name = info.Ex_name;
                    info.Descr = info.Ex_descr;
                }
                infoRecord.Created_by = cn.UserID;
                infoRecord.Created_when = DateTime.Now;
                info.InfoType = infoType;
                info.InfoExployee = infoEmployee;
                info.InfoPosition = infoPosition;
                info.InfoFunction = infoFunction;
                info.InfoRecord = infoRecord;
                infoTempCommittee.Add(info);
                ResetCommitteeNormal();
            }
            else //เพิ่มด้วย Wizard
            {
                if (Grid_SubCommittee.MasterTableView.Items.Count == 0)
                {
                    RadManager1.Alert("กรุณาระบุรายชื่อกรรมการ");
                    return;
                }
                else
                {
                    foreach (GridDataItem data in Grid_SubCommittee.MasterTableView.Items)
                    {
                        PrePurchaseRequestCommitteeInfo info = new PrePurchaseRequestCommitteeInfo();
                        HrmEmployeeInfo infoEmployee = new HrmEmployeeInfo();
                        MasterCommitteePositionInfo infoPosition = new MasterCommitteePositionInfo();
                        MasterCommitteeFunctionInfo infoFunction = new MasterCommitteeFunctionInfo();
                        HrmEmployeeInfo infoEmployeeDetail = new HrmEmployeeInfo();
                        SysCommitteeTypeInfo infoType = new SysCommitteeTypeInfo();
                        RecordInfo infoRecord = new RecordInfo();
                        info.Ref_no = Convert.ToInt32(data["Ref_no"].Text);
                        infoType.Seq = Convert.ToInt32(((RadioButtonList)data["Com_type"].FindControl("rblCommitteeType")).SelectedValue);
                        infoType.Name = ((RadioButtonList)data["Com_type"].FindControl("rblCommitteeType")).SelectedItem.Text;
                        infoPosition.Seq = Convert.ToInt32(data["InfoPosition.Seq"].Text);
                        infoPosition.Name = data["InfoPosition.Name"].Text;
                        infoFunction.Seq = Convert.ToInt32(data["InfoFunction.Seq"].Text);
                        infoFunction.Name = data["InfoFunction.Name"].Text;
                        if (infoType.Seq == 1) //เป็นบุคลากรภายใน
                        {
                            string emp_seq = ((RadComboBox)data["Internal"].FindControl("cbGridInternalName")).Text;
                            if (emp_seq.Length == 0)
                            {
                                RadManager1.Alert("กรุณาระบุรายชื่อกรรมการให้ถูกต้อง ครบถ้วน");
                                LoadGridSubCommittee();
                                return;
                            }
                            infoEmployee.Seq = Convert.ToInt32(((RadComboBox)data["Internal"].FindControl("cbGridInternalName")).SelectedValue);
                            infoEmployee.Name = ((RadComboBox)data["Internal"].FindControl("cbGridInternalName")).Text;
                            infoEmployeeDetail = bllEmployee.GetHrmEmployee(Convert.ToInt32(infoEmployee.Seq));
                            info.Name = infoEmployee.Name;
                            info.Descr = (infoEmployeeDetail.InfoJobSite.Name.Length > 0 ? " <b>หน่วยงาน : </b>" + infoEmployeeDetail.InfoJobSite.Name : "")
                                + (infoEmployeeDetail.InfoPosition.Name.Length > 0 ? " <b>ตำแหน่ง :</b>" + infoEmployeeDetail.InfoPosition.Name : "")
                                + (infoEmployeeDetail.InfoClass.Name.Length > 0 ? " <b>ระดับ :</b>" + infoEmployeeDetail.InfoClass.Name : "");
                        }
                        else
                        {
                            info.Ex_name = ((RadTextBox)data["External"].FindControl("txtGridExternalName")).Text;
                            if (info.Ex_name.Length == 0)
                            {
                                RadManager1.Alert("กรุณาระบุรายชื่อกรรมการให้ถูกต้อง ครบถ้วน");
                                LoadGridSubCommittee();
                                return;
                            }
                            info.Ex_descr = ((RadTextBox)data["External"].FindControl("txtGridExternalDescr")).Text;
                            info.Name = info.Ex_name;
                            info.Descr = info.Ex_descr;
                        }
                        infoRecord.Created_by = cn.UserID;
                        infoRecord.Created_when = DateTime.Now;
                        info.InfoType = infoType;
                        info.InfoExployee = infoEmployee;
                        info.InfoPosition = infoPosition;
                        info.InfoFunction = infoFunction;
                        info.InfoRecord = infoRecord;
                        infoTempCommittee.Add(info);
                    }
                    ResetCommitteeWizard();
                }
            }

            for (int i = 0; i < infoTempCommittee.Count; i++)
            {
                infoListCommittee.Add(infoTempCommittee[i]);
            }
            ViewState["Committee"] = infoListCommittee;
            panelAddCommittee_Normal.Visible = false;
            panelAddCommittee_Wizard.Visible = true;
            LoadGridCommittee();
        }

        protected void ResetCommitteeNormal()
        {
            txtCommitteeRefno.Text = "";
            cbCommitteeInternalName.ClearSelection();
            cbCommitteeInternalName.Text = "";
            txtCommitteeExternalName.Text = "";
            txtCommitteeExternalDescr.Text = "";
            cbCommitteePosition.ClearSelection();
            cbCommitteePosition.Text = "";
            cbCommitteeFunction.ClearSelection();
            cbCommitteeFunction.Text = "";
        }

        protected void ResetCommitteeWizard()
        {
            cbPurchaseMethod.ClearSelection();
            cbPurchaseMethod.Text = "";
            panelCommitteeGroup.Visible = false;
            Grid_SubCommittee.Visible = false;
        }

        protected void Delete_Committee_Click(object sender, EventArgs e)
        {
            int[] data_value = new int[Grid_Committee.MasterTableView.GetSelectedItems().Length];
            int item = Grid_Committee.MasterTableView.GetSelectedItems().Length;
            foreach (GridDataItem data in Grid_Committee.MasterTableView.GetSelectedItems())
            {
                item = item - 1;
                data_value[item] = data.ItemIndex;
            }

            for (int i = 0; i < data_value.Length; i++)
            {
                ((List<PrePurchaseRequestCommitteeInfo>)ViewState["Committee"]).RemoveAt(data_value[i]);
            }

            LoadGridCommittee();
        }

        protected void ShowGrid_File_Click(object sender, EventArgs e)
        {
            LoadGridFile();
        }

        protected void AddNew_File_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList_File, panelGrid_File, panelCommand_File);
            LoadValidateFile();
        }

        protected void AddNewSave_File_Click(object sender, EventArgs e)
        {
            IList<DocumentInfo> infoListFile = new List<DocumentInfo>();
            FileInfo infoFile = new FileInfo(hdSourceFile.Value);
            DocumentInfo info = new DocumentInfo();
            RecordInfo infoRecord = new RecordInfo();
            if (ViewState["File"] != null)
            {
                infoListFile = (List<DocumentInfo>)ViewState["File"];
            }
            infoRecord.Created_by = cn.UserID;
            infoRecord.Created_when = DateTime.Now;
            info.File_info = infoFile;
            info.Name = txtFileName.Text;
            info.Dest_path = hdSourceFile.Value;
            info.InfoRecord = infoRecord;
            infoListFile.Add(info);
            ViewState["File"] = infoListFile;
            LoadGridFile();
        }

        protected void Delete_File_Click(object sender, EventArgs e)
        {
            int[] data_value = new int[Grid_File.MasterTableView.GetSelectedItems().Length];
            int item = Grid_File.MasterTableView.GetSelectedItems().Length;
            foreach (GridDataItem data in Grid_File.MasterTableView.GetSelectedItems())
            {
                item = item - 1;
                data_value[item] = data.ItemIndex;
            }

            for (int i = 0; i < data_value.Length; i++)
            {
                ((List<DocumentInfo>)ViewState["File"]).RemoveAt(data_value[i]);
            }

            LoadGridFile();
        }

        protected void Grid_Item_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridItem();
        }

        protected void Grid_SubItem_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridSubItem();
        }

        protected void Grid_Committee_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridCommittee();
        }

        protected void Grid_File_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridFile();
        }
                
        protected void OnAjaxUpdate(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTip(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTip(string elementID, UpdatePanel panel)
        {
            string[] all_value = elementID.Split(new string[] { ":" }, StringSplitOptions.None);
            if (all_value[0] == "Item")
            {
                Session["Resource_Item_Id"] = all_value[1];
                Session["Expense_Id"] = null;
            }
            else
            {
                Session["Resource_Item_Id"] = null;
                Session["Expense_Id"] = all_value[1];
            }
            Control ctrl = Page.LoadControl("../UserControl/ICM_Pre_Purchase_Request.ascx");
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        protected void OnAjaxUpdate2(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTip2(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTip2(string elementID, UpdatePanel panel)
        {
            string[] all_value = elementID.Split(new string[] { ":" }, StringSplitOptions.None);
            if (all_value[0] == "Item")
            {
                Session["Resource_Item_Id"] = all_value[1];
                Session["Expense_Id"] = null;
            }
            else
            {
                Session["Resource_Item_Id"] = null;
                Session["Expense_Id"] = all_value[1];
            }
            Session["Resource_Item_Id"] = all_value[1];
            Control ctrl = Page.LoadControl("../UserControl/TIP_Item_Detail.ascx");
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        protected void Grid_SubItem_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                double qty = 0;
                double price = 0;
                Control target = e.Item.FindControl("lkName");
                GridDataItem dataBoundItem = e.Item as GridDataItem;

                RadNumericTextBox txtPrice = ((RadNumericTextBox)(dataBoundItem["Price"].FindControl("txtPrice")));
                RadNumericTextBox txtQty = ((RadNumericTextBox)(dataBoundItem["Qty"].FindControl("txtQty")));

                txtPrice.Attributes.Add("onFocus", "return Focus('" + txtPrice.ClientID + "','" + txtQty.ClientID + "')");
                txtQty.Attributes.Add("onFocus", "return Focus('" + txtPrice.ClientID + "','" + txtQty.ClientID + "')");
                txtPrice.Attributes.Add("onBlur", "return Blur('" + txtPrice.ClientID + "','" + txtQty.ClientID + "')");
                txtQty.Attributes.Add("onBlur", "return Blur('" + txtPrice.ClientID + "','" + txtQty.ClientID + "')");

                if (((RadNumericTextBox)(dataBoundItem["Qty"].FindControl("txtQty"))).Value.ToString().Length > 0)
                {
                    qty = double.Parse(((RadNumericTextBox)(dataBoundItem["Qty"].FindControl("txtQty"))).Value.ToString());
                }
                if (((RadNumericTextBox)(dataBoundItem["Price"].FindControl("txtPrice"))).Value.ToString().Length > 0)
                {
                    price = double.Parse(((RadNumericTextBox)(dataBoundItem["Price"].FindControl("txtPrice"))).Value.ToString());
                }

                sumValue += (qty * price);
                if (!Object.Equals(target, null))
                {
                    if (!Object.Equals(this.TipEachItem, null))
                    {
                        if (dataBoundItem["InfoItem.Seq"].Text.Length > 0 && dataBoundItem["InfoItem.Seq"].Text != "&nbsp;")
                        {
                            this.TipEachItem.TargetControls.Add(target.ClientID, "Item:" + dataBoundItem["InfoItem.Seq"].Text, true);
                        }
                        else
                        {
                            this.TipEachItem.TargetControls.Add(target.ClientID, "Expense:" + dataBoundItem["InfoExpense.Seq"].Text, true);
                        }
                    }
                }
            }
            else if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["Descr"].Controls.Add(new LiteralControl("<span style='color: Black; font-weight: bold;'>วงเงินจัดหาทั้งหมด :</span> "));
                footer["Descr"].HorizontalAlign = HorizontalAlign.Right;
                ((RadNumericTextBox)footer["Price"].FindControl("txtTotalPrice")).Value = Double.Parse(sumValue.ToString());
            }
        }

        protected void Grid_Item_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (nCount == 0)
            {
                totalPrice = 0;
            }
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                nCount++;
                double qty = 0;
                double price = 0;
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                Control target = e.Item.FindControl("lkName");

                if (dataBoundItem["Qty"].Text.Length > 0)
                {
                    qty = double.Parse(dataBoundItem["Qty"].Text);
                }
                if (((Label)(dataBoundItem["Price"].FindControl("lblPrice"))).Text.Length > 0)
                {
                    price = double.Parse(((Label)(dataBoundItem["Price"].FindControl("lblPrice"))).Text);
                }

                totalPrice += (qty * price);

                if (!Object.Equals(target, null))
                {
                    if (!Object.Equals(this.TipItemDetail, null))
                    {
                        this.TipItemDetail.TargetControls.Add(target.ClientID, "Item:" + dataBoundItem["InfoItem.Seq"].Text, true);
                    }
                }
            }
            else if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["Descr"].Controls.Add(new LiteralControl("<span style='color: Black; font-weight: bold;'>วงเงินจัดหาทั้งหมด :</span> "));
                ((Label)footer["Price"].FindControl("lblTotalPrice")).Text = totalPrice.ToString("###,###,##0.00");
                nCount = 0;
            }
        }

        protected void cbPurchaseMethod_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            double sumAmount = 0;
            if (ViewState["PprItem"] != null)
            {
                for (int i = 0; i < ((List<PrePurchaseRequestItemInfo>)ViewState["PprItem"]).Count; i++)
                {
                    Nullable<int> qty = ((List<PrePurchaseRequestItemInfo>)ViewState["PprItem"])[i].Qty;
                    Nullable<double> price = ((List<PrePurchaseRequestItemInfo>)ViewState["PprItem"])[i].Price;
                    sumAmount += (Convert.ToDouble(qty) * Convert.ToDouble(price));
                }
                cbPurchaseMethod.DataSource = bllPurchaseMap.GetMasterPurchaseMappingWithCondition(Convert.ToInt32(this.PurchaseType), Convert.ToInt32(hdRule.Value), sumAmount);
                cbPurchaseMethod.DataBind();
            }
        }

        protected void cbPurchaseMethod_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            panelCommitteeGroup.Visible = (cbPurchaseMethod.Text.Length > 0);
            if (cbPurchaseMethod.Text.Length > 0)
            {
                LoadCommitteeFunction(Convert.ToInt32(cbPurchaseMethod.SelectedValue));
            }
        }

        protected void rblCommitteeType_SelectedIndexChanged(object sender, EventArgs e)
        {
            panelInternal.Visible = (rblCommitteeType.SelectedValue == "1");
            panelExternal.Visible = (rblCommitteeType.SelectedValue == "2");
            SetValidationCommittee();
        }

        protected void SetValidationCommittee()
        {
            RequiredFieldValidator valCommitteeRefno = new RequiredFieldValidator();
            valCommitteeRefno.ID = "ValtxtCommitteeRefno";
            valCommitteeRefno.ControlToValidate = "txtCommitteeRefno";
            valCommitteeRefno.SetFocusOnError = true;
            valCommitteeRefno.Display = ValidatorDisplay.Dynamic;
            valCommitteeRefno.ErrorMessage = "* กรุณาระบุชุดที่ *";
            panelValtxtCommitteeRefno.Controls.Add(valCommitteeRefno);
            RequiredFieldValidator valCommitteeInternalName = new RequiredFieldValidator();
            valCommitteeInternalName.ID = "ValcbCommitteeInternalName";
            valCommitteeInternalName.ControlToValidate = "cbCommitteeInternalName";
            valCommitteeInternalName.SetFocusOnError = true;
            valCommitteeInternalName.Display = ValidatorDisplay.Dynamic;
            valCommitteeInternalName.ErrorMessage = "* กรุณาระบุชื่อกรรมการ *";
            panelValcbCommitteeInternalName.Controls.Add(valCommitteeInternalName);
            RequiredFieldValidator valCommitteeExternalName = new RequiredFieldValidator();
            valCommitteeExternalName.ID = "ValtxtCommitteeExternalName";
            valCommitteeExternalName.ControlToValidate = "txtCommitteeExternalName";
            valCommitteeExternalName.SetFocusOnError = true;
            valCommitteeExternalName.Display = ValidatorDisplay.Dynamic;
            valCommitteeExternalName.ErrorMessage = "* กรุณาระบุชื่อกรรมการ *";
            panelValtxtCommitteeExternalName.Controls.Add(valCommitteeExternalName);
            RequiredFieldValidator valCommitteePosition = new RequiredFieldValidator();
            valCommitteePosition.ID = "ValcbCommitteePosition";
            valCommitteePosition.ControlToValidate = "cbCommitteePosition";
            valCommitteePosition.SetFocusOnError = true;
            valCommitteePosition.Display = ValidatorDisplay.Dynamic;
            valCommitteePosition.ErrorMessage = "* กรุณาระบุตำแหน่งกรรมการ *";
            panelValcbCommitteePosition.Controls.Add(valCommitteePosition);
            RequiredFieldValidator valCommitteeFunction = new RequiredFieldValidator();
            valCommitteeFunction.ID = "ValcbCommitteeFunction";
            valCommitteeFunction.ControlToValidate = "cbCommitteeFunction";
            valCommitteeFunction.SetFocusOnError = true;
            valCommitteeFunction.Display = ValidatorDisplay.Dynamic;
            valCommitteeFunction.ErrorMessage = "* กรุณาระบุหน้าที่กรรมการ *";
            panelValcbCommitteeFunction.Controls.Add(valCommitteeFunction);
        }

        protected void rblAddCommittee_SelectedIndexChanged(object sender, EventArgs e)
        {
            panelAddCommittee_Normal.Visible = (rblAddCommittee.SelectedValue == "Normal");
            panelAddCommittee_Wizard.Visible = (rblAddCommittee.SelectedValue == "Wizard");
            if (rblAddCommittee.SelectedValue == "Normal")
            {
                SetValidationCommittee();
            }
        }

        protected void cbCommitteeInternalName_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            IList<HrmEmployeeInfo> infoList = bllEmployee.GetHrmEmployee(e.Text);
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + ItemsPerRequest, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cbCommitteeInternalName.Items.Add(new RadComboBoxItem(infoList[i].Name, infoList[i].Seq.ToString()));
                TableRow tr = new TableRow();
                TableCell tdJobSite = new TableCell();
                Label lblJobSite = new Label();
                lblJobSite.Text = infoList[i].InfoJobSite.Name;
                tdJobSite.Width = Unit.Pixel(200);
                tdJobSite.Controls.Add(lblJobSite);
                tr.Cells.Add(tdJobSite);
                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].Name;
                tdName.Width = Unit.Pixel(150);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);
                TableCell tdPosition = new TableCell();
                Label lblPosition = new Label();
                lblPosition.Text = infoList[i].InfoPosition.Name;
                tdPosition.Width = Unit.Pixel(150);
                tdPosition.Controls.Add(lblPosition);
                tr.Cells.Add(tdPosition);
                TableCell tdClass = new TableCell();
                Label lblClass = new Label();
                lblClass.Text = infoList[i].InfoClass.Name;
                tdClass.Width = Unit.Pixel(190);
                tdClass.Controls.Add(lblClass);
                tr.Cells.Add(tdClass);
                ((Table)cbCommitteeInternalName.Items[j].FindControl("tableCommmitteeInternalName")).Controls.Add(tr);
                j++;
            }
            
            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }

        private static string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";
            
            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }

        protected void Grid_SubCommittee_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                GridDataItem dataBoundItem = e.Item as GridDataItem;

                RadioButtonList rblCommitteeType = ((RadioButtonList)(dataBoundItem["Com_type"].FindControl("rblCommitteeType")));
                Panel panelInternalName = ((Panel)(dataBoundItem["Internal"].FindControl("panelGridCommitteeInternalName")));
                Panel panelExternalName = ((Panel)(dataBoundItem["External"].FindControl("panelGridCommitteeExternalName")));
                Panel panelExternalDescr = ((Panel)(dataBoundItem["External"].FindControl("panelGridCommitteeExternalDescr")));

                panelExternalName.Attributes.Add("style", "visibility:hidden");
                panelExternalDescr.Attributes.Add("style", "visibility:hidden");
                rblCommitteeType.Items[0].Attributes.Add("onclick", "return ChangeCommitteeInternal('" + panelInternalName.ClientID + "','" + panelExternalName.ClientID + "','" + panelExternalDescr.ClientID + "')");
                rblCommitteeType.Items[1].Attributes.Add("onclick", "return ChangeCommitteeExternal('" + panelInternalName.ClientID + "','" + panelExternalName.ClientID + "','" + panelExternalDescr.ClientID + "')");
            }
        }

        protected void btnAddGroupCommittee_Click(object sender, EventArgs e)
        {
            btnAddGroupCommittee.Enabled = false;
            IList<PrePurchaseRequestCommitteeInfo> infoListCommittee = new List<PrePurchaseRequestCommitteeInfo>();
            IList<PrePurchaseRequestCommitteeInfo> infoListAddCommittee = new List<PrePurchaseRequestCommitteeInfo>();
            if (ViewState["Committee"] != null)
            {
                infoListCommittee = (List<PrePurchaseRequestCommitteeInfo>)ViewState["Committee"];
            }
            ViewState["AddCommittee"] = null;
            Grid_SubCommittee.Visible = true;
            for (int i = 0; i < cblCommitteeFunction.Items.Count; i++)
            {
                if (cblCommitteeFunction.Items[i].Selected)
                {
                    foreach (Control child in tableNumCommitteeFunction.Rows[i].Cells[0].Controls)
                    {
                        if (child.GetType().ToString().Equals("Telerik.Web.UI.RadNumericTextBox")
                              && child.ID.IndexOf("txtFunction_") == 0)
                        {
                            RadNumericTextBox textbox = (RadNumericTextBox)child;
                            if (textbox.Text.Length > 0)
                            {
                                IList<MasterCommitteeMappingInfo> info = new List<MasterCommitteeMappingInfo>();
                                info = bllComMapping.GetMasterCommitteeMappingWithFunction(Convert.ToInt32(cbPurchaseMethod.SelectedValue), Convert.ToInt32(cblCommitteeFunction.Items[i].Value));
                                Nullable<int> nMaxRefNo = 0; 
                                for (int j = 0; j < infoListCommittee.Count; j++)
                                {
                                    if (nMaxRefNo < infoListCommittee[j].Ref_no)
                                    {
                                        nMaxRefNo = infoListCommittee[j].Ref_no;
                                    }
                                }
                                nMaxRefNo = nMaxRefNo + 1;
                                for (int k = 0; k < Convert.ToInt32(textbox.Text); k++)
                                {
                                    for (int j = 0; j < info.Count; j++)
                                    {
                                        PrePurchaseRequestCommitteeInfo infoCommittee = new PrePurchaseRequestCommitteeInfo();
                                        infoCommittee.Ref_no = nMaxRefNo;
                                        infoCommittee.InfoPosition = info[j].InfoPosition;
                                        infoCommittee.InfoFunction = info[j].InfoFunction;
                                        infoListAddCommittee.Add(infoCommittee);
                                    }
                                    nMaxRefNo = nMaxRefNo + 1;
                                }
                            }
                        }
                    }
                }
            }
            ViewState["AddCommittee"] = infoListAddCommittee;
            LoadGridSubCommittee();
        }

        protected void cbGridInternalName_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            IList<HrmEmployeeInfo> infoList = bllEmployee.GetHrmEmployee(e.Text);
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + ItemsPerRequest, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                ((RadComboBox)sender).Items.Add(new RadComboBoxItem(infoList[i].Name, infoList[i].Seq.ToString()));
                TableRow tr = new TableRow();
                TableCell tdJobSite = new TableCell();
                Label lblJobSite = new Label();
                lblJobSite.Text = infoList[i].InfoJobSite.Name;
                tdJobSite.Width = Unit.Pixel(100);
                tdJobSite.Controls.Add(lblJobSite);
                tr.Cells.Add(tdJobSite);
                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].Name;
                tdName.Width = Unit.Pixel(100);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);
                TableCell tdPosition = new TableCell();
                Label lblPosition = new Label();
                lblPosition.Text = infoList[i].InfoPosition.Name;
                tdPosition.Width = Unit.Pixel(100);
                tdPosition.Controls.Add(lblPosition);
                tr.Cells.Add(tdPosition);
                TableCell tdClass = new TableCell();
                Label lblClass = new Label();
                lblClass.Text = infoList[i].InfoClass.Name;
                tdClass.Width = Unit.Pixel(100);
                tdClass.Controls.Add(lblClass);
                tr.Cells.Add(tdClass);
                ((Table)((RadComboBox)sender).Items[j].FindControl("tableGridInternalName")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }

        #region Amp Function

        //public void LoadJobSiteTree()
        //{
            //IList<TreeInfo> info = bllTree.GetJobSiteTree();
            //RadTreeView tree = (RadTreeView)cbJobSite.Items[0].FindControl("TreeViewJobSite");
            
            //tree.DataSource = info;
            //tree.DataBind();

        //}

        //private void SettingSelectJobSiteTree(string value)
        //{
        //    RadTreeView tree = (RadTreeView)cbJobSite.Items[0].FindControl("TreeViewJobSite");
        //    RadTreeNode node = tree.FindNodeByValue(value);
        //    if (node != null)
        //    {
        //        node.Selected = true;
        //        cbJobSite.Text = node.Text;
        //        //cbJobSite.SelectedIndex = node.Index;
        //    }
        //}

        protected void LoadYearType()
        {
            IList<SysYearTypeInfo> infoList = bllYearType.GetSysYearType();
            cbYearType.DataSource = infoList;
            cbYearType.DataBind();
        }

        #endregion

        protected void clearFilter_Item_Click(object sender, EventArgs e)
        {
            foreach (GridColumn column in Grid_Item.MasterTableView.Columns)
            {
                column.CurrentFilterFunction = GridKnownFunction.NoFilter;
                column.CurrentFilterValue = string.Empty;
            }
            Grid_Item.MasterTableView.FilterExpression = string.Empty;
            LoadGridItem();
        }

        protected void clearFilter_Committee_Click(object sender, EventArgs e)
        {
            foreach (GridColumn column in Grid_Committee.MasterTableView.Columns)
            {
                column.CurrentFilterFunction = GridKnownFunction.NoFilter;
                column.CurrentFilterValue = string.Empty;
            }
            Grid_Committee.MasterTableView.FilterExpression = string.Empty;
            LoadGridCommittee();
        }

        protected void clearFilter_File_Click(object sender, EventArgs e)
        {
            foreach (GridColumn column in Grid_File.MasterTableView.Columns)
            {
                column.CurrentFilterFunction = GridKnownFunction.NoFilter;
                column.CurrentFilterValue = string.Empty;
            }
            Grid_File.MasterTableView.FilterExpression = string.Empty;
            LoadGridFile();
        }

        private void GetUserJobSite(int emp_seq)
        {
            string[] jobsite_value = bllPersonal.GetUserJobSite(emp_seq);
            cbJobSite.SelectedValue = jobsite_value[0];
            cbJobSite.Text = jobsite_value[1];
            //SettingSelectJobSiteTree(jobsite_value);
        }

        private void SetViewStateJobSite(string value)
        {
            ViewState["JobSite"] = value;
        }

        private void SetViewStateYear(string value)
        {
            ViewState["Year"] = value;
        }

        private void LoadValidateItem()
        {
            string UseMethod = Request.QueryString["um"].ToString();
            if (UseMethod == "1")
            {
                RequiredFieldValidator val = new RequiredFieldValidator();
                val.ID = "ValcbProject";
                val.ControlToValidate = "cbProject";
                val.SetFocusOnError = true;
                val.Display = ValidatorDisplay.Dynamic;
                val.ErrorMessage = "* กรุณาระบุรายจ่ายจากแผนการใช้จ่ายงบประมาณ *";
                panelValcbProject.Controls.Add(val);
                panelProject.Visible = true;
                panelOperation.Visible = false;
            }
            else if (UseMethod == "2")
            {
                RequiredFieldValidator valOperation = new RequiredFieldValidator();
                valOperation.ID = "ValcbOperation";
                valOperation.ControlToValidate = "cbOperation";
                valOperation.SetFocusOnError = true;
                valOperation.Display = ValidatorDisplay.Dynamic;
                valOperation.ErrorMessage = "* กรุณาระบุรายจ่ายจากอนุมัติหลักการ *";
                panelValcbOperation.Controls.Add(valOperation);
                panelProject.Visible = false;
                panelOperation.Visible = true;
            }
        }

        private void LoadValidateFile()
        {
            RequiredFieldValidator valFileName = new RequiredFieldValidator();
            valFileName.ID = "ValtxtFileName";
            valFileName.ControlToValidate = "txtFileName";
            valFileName.SetFocusOnError = true;
            valFileName.Display = ValidatorDisplay.Dynamic;
            valFileName.ErrorMessage = "* กรุณาระบุชื่อไฟล์ *";
            panelValtxtFileName.Controls.Add(valFileName);
            RequiredFieldValidator valAttachment = new RequiredFieldValidator();
            valAttachment.ID = "Valattachment";
            valAttachment.ControlToValidate = "attachment";
            valAttachment.SetFocusOnError = true;
            valAttachment.Display = ValidatorDisplay.Dynamic;
            valAttachment.ErrorMessage = "* กรุณาระบุที่อยู่ไฟล์ *";
            panelValattachment.Controls.Add(valAttachment);
        }
    }
}
